#include "command.h"
//服务端
int handler_gets(int sockfd, data msg, char * file_path, MYSQL *mysql, char *name){
    //当前msg.args中存储的是数据库中file_path的信息
    //通过file_path, user_id和is_dalate来判断文件是否存在
    //构建sql语句
    char sql_buf[1024] = {0};
    //sprintf(sql_buf, "select file_hash from file where user id = (select user_id from user where username = '%s') and file_path = '%s' and is_deleted = 0", name, msg.args);
    snprintf(sql_buf, sizeof(sql_buf), "select file_hash from file where user_id = (select user_id from user where user_name = '%.*s') and file_name = '%.*s' and is_deleted = 0", 255, name, 255, msg.args);
    //进行查询
    mysql_query(mysql, sql_buf);
    //获取返回值
    MYSQL_RES *result = mysql_store_result(mysql);
    //处理查询不到任何东西的逻辑，发送标记位，退出
    if(result == NULL || mysql_num_rows(result) == 0){
        int flag = 0;
        send(sockfd, &flag, sizeof(int), MSG_NOSIGNAL);
        return 0;
    }
    //从返回值中取出返回结果存入buf数组中
    char buf[512] = {0};
    MYSQL_ROW row;
    while((row = mysql_fetch_row(result))){
        for (int i = 0; i < mysql_num_fields(result); i++){
            strncat(buf, row[i], strlen(row[i]));
        }
    }
    //释放结果集
    mysql_free_result(result);
    //标记位返回文件是否存在，1表示存在，0表示不存在
    int count = -10000000;
    if(strlen(buf) == 0){
        //文件不存在
        count = 0;
        //发送count给客户端
        send(sockfd, &count, sizeof(int), MSG_NOSIGNAL);
        return 0;
    }
    //文件存在
    count = 1;
    send(sockfd, &count, sizeof(int), MSG_NOSIGNAL);

    //接收文件哈希值
    char buf_hash[512] = {0};
    recv(sockfd, buf_hash, sizeof(buf_hash), MSG_WAITALL);

    int flag = 1;//判断客户端文件是否完整，1不完整，0完整
    if(!strcmp(buf, buf_hash)){//文件完整
        flag = 0;
        send(sockfd, &flag, sizeof(int), MSG_NOSIGNAL);
        return 0;
    }
    //文件不完整
    send(sockfd, &flag, sizeof(int), MSG_NOSIGNAL);
    //发送文件
    //打开文件
    char curr_path[1024] = {0};
    char *path = getcwd(curr_path, sizeof(curr_path));
    char *p1 = "file";
    char *p = "/";
    strcat(path, p);
    strcat(path, p1);
    strcat(path, p);
    strcat(path, buf);
    printf("打开文件的路径 = %s\n", path);
    int file_fd = open(path, O_RDWR);
    //计算服务端文件的总大小
    struct stat size;
    fstat(file_fd, &size);
    printf("打开的文件大小 = %ld\n", size.st_size);
    //接收客户端下载文件存在的大小
    off_t cilent_size;
    recv(sockfd, &cilent_size, sizeof(off_t), MSG_WAITALL);
    //发送总文件的大小
    send(sockfd, &size.st_size, sizeof(off_t), MSG_NOSIGNAL);
    //计算需要发送的文件大小
    off_t send_size = size.st_size - cilent_size;
    //发送文件
    
    sendfile(sockfd, file_fd, &cilent_size, send_size);
    printf("文件发送完成\n");
    log_log("INFO","SERVE","文件下载成功");
    return 0;

}